﻿using ApiTemplate.Common;
using ApiTemplate.Entity.Input.UserInfo;
using ApiTemplate.Entity.Output.UserInfo;

namespace ApiTemplate.Application
{
    /// <summary>
    /// 用户相关服务
    /// </summary>
    public class UserInfoApplication: BaseApplication, IUserInfoApplication
    {
        /// <summary>
        /// 用户相关数据访问层
        /// </summary>
        public IUserInfoDAL UserInfoDAL { get; set; }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<UserLoginOutput> UserLoginAsync(UserLoginInput input)
        {
            //密码使用des加密
            input.PassWord = EncryptionHelper.DesEncrypt(input.PassWord);

            UserLoginOutput user = UserInfoDAL.UserLoginAsync(input);
            if (user == null)
            {
                throw new BusinessException
                {
                    Code = ErrorCode.DataDeleted,
                    ErrorMessage = "账号密码不匹配"
                };
            }
            else
            {
                #region 生成授权部分，此处使用最简单的token授权
                //生成一个token，这里使用userId和用户名混合加密生成
                string toekn = EncryptionHelper.DesEncrypt(user.Id + user.UserName);
                await CacheHelper.SetEntityAsync(toekn, user, 30);//存储到缓存中
                user.Token = toekn;
                #endregion
                return user;
            }
        }
    }
}
